<template>
  <div class="app-container login">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm"   class="demo-ruleForm">
        <el-form-item label="" prop="userName">
            <el-input v-model="ruleForm.userName" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="" prop="password">
            <el-input v-model="ruleForm.password" placeholder="请输入密码" show-password></el-input>
        </el-form-item>

        <el-form-item label="" prop="imgCode">
            <div class="imgCode ">
              <el-input v-model="ruleForm.imgCode" placeholder="验证码" @keyup.enter.native="submitForm('ruleForm')" ></el-input>
              <img  class="imgBox" @click="img_codeClick" ref="img_codeRef"  :src="$upLoadApi + '/login/img_code'" alt="">
            </div>
        </el-form-item>
        <el-form-item >
          <div class="" style="text-align:center">
            <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </div>
        </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'loginCard',
  data () {
    return {
      ruleForm: {
        imgCode: '',
        userName: '',
        password: ''
      },
      rules: {
        imgCode: { required: true, message: '请输入验证码', trigger: 'blur' },
        userName: { required: true, message: '请输入用户名称', trigger: 'blur' },
        password: { required: true, message: '请输入用户名称', trigger: 'blur' }
      },
      redirect: undefined
    }
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  mounted () {
    this.img_codeClick()
  },
  methods: {
    // 点击图片 获取图片验证码
    img_codeClick () {
      this.$refs.img_codeRef.src = this.$upLoadApi + '/login/img_code?time' + new Date()
    },
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) {
          return false
        } else {
          this.$store.dispatch('user/Login', this.ruleForm).then(() => {
            this.$router.push({ path: this.redirect || '/' }).catch(() => {})
          }).catch(() => {
            this.img_codeClick()
            this.loading = false
          })
        }
      })
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style  lang="scss" scoped>
.box-card{
  width: 450px;
  margin: 10vw auto;
  .clearfix{
      text-align: center;
      font-size: 18px;
  }
  .imgCode{
    display: flex;
    align-items: center;
    .imgBox{
      margin-left: 10px;
      width:90px;
      height:40px
    }
  }
}
</style>
